<template>
    <page-meta :page-style="'overflow:' + (isopenPop ? 'hidden' : 'visible')"> </page-meta>
    <Decorate
        :datas="options"
        pageType="active"
        @updataCoupon="getDecorate()"
        @openPop="isopenPop = true"
        @closePop="isopenPop = false" />
</template>
<script setup>
import { reactive, ref } from 'vue';
import request from '@/request';
import storage from '@/commons/storage';
import { onShow, onHide, onUnload, onShareAppMessage } from '@dcloudio/uni-app';
import Decorate from '@/components/decorate';
import { useTrace } from '@/commons/trace';
import { getParamsBySceneHook, getTabBarInfo } from '@/hooks';
import { floatDivide, isNotEmpty } from '@/commons/utils.js';
import router from '@/router';
const { traceStart, traceLoad, traceStay } = useTrace({ autoLoad: true });
const props = defineProps(['id', 'shopId', 'scene']);
let isopenPop = ref(false);
const options = reactive({ data: { templateName: '', components: [] }, shareImg: '', shareTitle: '' });

onShow(() => {
    isopenPop.value = false;
    traceStart();
    getDecorate();
});
onHide(() => {
    traceStay();
});
onUnload(() => {
    traceStay();
});
// 转换优惠券内容
const couponContent = obj => {
    const { couponPrerequisites, couponMatch, couponPrerequisitesAdditional, couponDiscountContent } = obj;
    const pre = [
        '无门槛，',
        `满${floatDivide(couponPrerequisitesAdditional, 100)}元，`,
        `满${couponPrerequisitesAdditional}件，`
    ];
    const num = [`全部商品`, `部分商品`, '部分商品'];
    return (pre[couponPrerequisites - 1] || '') + (num[couponMatch - 1] || '');
};
const getDecorate = async () => {
    if (props.scene) {
        // 分享弹窗生成的二维码跳转的
        const res = await getParamsBySceneHook(props.scene, 1);
        res?.shopId && storage.set('ZW_SHOP_ID', Number(res?.shopId));
        // 重定向首页，避免切换店铺返回后有scene参数，无法切换店铺更改缓存
        const url = res?.id ? `/pages-activity/dynamic/index?id=${res?.id}` : '/pages-activity/dynamic/index';
        router.redirectTo({
            url
        });
    } else if (props.shopId) {
        // 如果参数上带有shopId,比如分享朋友圈，短链，分享给好友的链接
        storage.set('ZW_SHOP_ID', Number(props.shopId));
        // 重定向首页，避免切换店铺返回后有scene参数，无法切换店铺更改缓存
        const url = props.id ? `/pages-activity/dynamic/index?id=${props.id}` : '/pages-activity/dynamic/index';
        router.redirectTo({
            url
        });
    }
    request('decorateServ', {
        id: props.id,
        shopId: storage.get('ZW_SHOP_ID'),
        isPreview: 2
    }).then(async res => {
        if (Object.keys(res.data).length) {
            let getData = JSON.parse(JSON.stringify(options.data));
            Object.assign(getData, res.data);
            options.shareImg = getData.shareImg;
            options.shareTitle = getData.shareTitle;
            let productIds = [];
            let seckillIds = [];
            let groupbuyIds = [];
            let couponIds = [];

            let components = JSON.parse(getData.components);
            components.forEach(async (item, index) => {
                if (item.component.name == 'PlaceHolderView') {
                    components.splice(index, 1);
                    return;
                }
                if (item.component.name == 'product') {
                    productIds = [...productIds, ...item.options.imgList];
                } else if (item.component.name == 'seckill') {
                    seckillIds = [...seckillIds, ...item.options.imgList];
                } else if (item.component.name == 'groupbuy') {
                    if (item.options.addType == 1) {
                        //手动添加
                        groupbuyIds = [...groupbuyIds, ...item.options.imgList];
                    }
                } else if (item.component.name == 'coupon') {
                    couponIds = [...couponIds, ...item.options.imgList];
                }
            });
            let productData = [];
            let seckillData = [];
            let groupData = [];
            let couponData = [];
            if (couponIds.length) {
                couponData = await request('couponList', { couponIds: couponIds, userId: storage.get('userId') });
            }
            if (productIds.length) {
                productData = await request('goodsList', { goodsId: productIds });
            }
            if (seckillIds.length) {
                seckillData = await request('seckillList', { activityId: seckillIds });
            }
            if (groupbuyIds.length) {
                groupData = await request('seckillListManual', { activityId: groupbuyIds, tenantId: 19 });
            }
            let param = await Promise.all(
                components.map(async item => {
                    const name = item.component.name;
                    const imgLists = {
                        product: isNotEmpty(productData?.data) ? productData?.data : [],
                        seckill: isNotEmpty(seckillData?.data) ? seckillData?.data : [],
                        groupbuy: isNotEmpty(groupData?.data) ? groupData?.data : [],
                        coupon: isNotEmpty(couponData?.data) ? couponData?.data : []
                    };
                    if (name == 'product' || name == 'seckill') {
                        item.options.imgList.forEach((id, indexs) => {
                            let proItem = imgLists[name].filter(val => val.id == id);
                            if (proItem.length) {
                                item.options.imgList[indexs] = proItem[0];
                            } else {
                                item.options.imgList[indexs] = null;
                            }
                        });
                    }

                    if (name == 'coupon') {
                        item.options.imgList.forEach((id, indexs) => {
                            let proItem = imgLists[name].filter(val => val.id == id);
                            if (proItem.length) {
                                item.options.imgList[indexs] = proItem.map(
                                    ({ couponAcquiredNumber, id, couponInfo, couponId }) => {
                                        const item = {
                                            ...couponInfo
                                        };
                                        // receiveStatus:1表示已领完 2表示领取已达上限
                                        item.receiveStatus =
                                            item.couponTotal - couponAcquiredNumber == 0
                                                ? 1
                                                : item?.acquireLimit
                                                ? '2'
                                                : '';
                                        item.content = couponContent(item);
                                        item.id = id;
                                        item.couponId = couponId;
                                        return item;
                                    }
                                )[0];
                            } else {
                                item.options.imgList[indexs] = null;
                            }
                        });
                    }
                    if (name == 'groupbuy') {
                        if (item.options.addType == 1) {
                            item.options.imgList.forEach((id, indexs) => {
                                let proItem = imgLists[name].filter(val => val.id == id);
                                if (proItem.length) {
                                    item.options.imgList[indexs] = proItem[0];
                                } else {
                                    item.options.imgList[indexs] = null;
                                }
                            });
                        } else {
                            let typeList = ['have_group_goods_num', 'activity_end_time', 'activity_start_time'];
                            const groupAuto = await request('groupList', {
                                autogather: 1,
                                direction: 'desc',
                                activityType: item.options.groupType,
                                reorder: typeList[item.options.rule - 1]
                            });
                            item.options.imgList = isNotEmpty(groupAuto?.data) ? groupAuto?.data : [];
                        }
                    }
                    return item;
                })
            );
            // 过滤删除商品，当选择商品全部删除后，删除组件不再显示
            options.data.components = param
                .map(item => {
                    item.options.imgList = item?.options?.imgList?.filter(fItem => fItem);
                    return item;
                })
                .filter(item => !item.options.imgList || item.options?.imgList.length > 0);
            uni.setNavigationBarTitle({ title: res.data.templateDesc });
            traceLoad('visit_page_activity', {
                activityId: options.data.id,
                activityName: options.data.templateDesc
            });
        }
    });
    getTabBarInfo();
};
onShareAppMessage(res => {
    return {
        title: options.shareTitle ? options.shareTitle : '',
        path: '/pages-activity/dynamic/index?shopId=' + storage.get('ZW_SHOP_ID') + '&id=' + props.id,
        imageUrl: options.shareImg ? options.shareImg : ''
    };
});
</script>
<style lang="scss" scoped></style>
